-- -*- coding: utf-8 -*-

require("api.json")
local object = require("api.object")

local io_module = {}

function io_module.parse_input_state(input_data)
    -- 解析输入状态
    -- Args:
    --     input_data: 输入的JSON字符串
    -- Returns:
    --     解析后的输入状态
    local success, input_state = pcall(json.decode, input_data)
    if success then
        return object.GameState.new(input_state)
    else
        io.stderr:write("JSON解析错误: " .. tostring(input_state) .. "\n")
        return {}
    end
end

function io_module.format_output_commands(commands)
    -- 格式化输出命令
    -- Args:
    --     commands: 命令列表
    -- Returns:
    --     格式化的JSON字符串
    local success, result = pcall(function()
        local cmds = {}
        for i, cmd in ipairs(commands) do
            cmds[i] = cmd:toDict()
        end
        return json.encode(cmds)
    end)

    if success then
        return result
    else
        io.stderr:write("JSON序列化错误: " .. tostring(result) .. "\n")
        return "[]"
    end
end

function io_module.input(path)
    local file = io.open(path, "r")
    local content = file:read("*all")
    file:close()
    return content
end

function io_module.output(s, file, is_commands)
    -- 为commands输出添加特殊标识前缀
    file = file or io.stdout
    is_commands = is_commands or false
    if file == io.stdout and is_commands then
        io.stdout:write("COMMANDS_OUTPUT:" .. s .. "\n")
    else
        file:write(s .. "\n")
    end
    file:flush()
end

return io_module
